package arrdemo;

public class arrDemo {

    public static void main(String[] args) {

        //查找
        int[] arr = {11, 22, 33, 44, 55, 66, 77, 88, 99, 120, 2147};
        int a = 44;

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == a) {
                System.out.println(i);
            }
        }


        int b = twoF(arr, a);
        System.out.println(b);
    }

    //定义二分法查找，参数为数组和要查找的元素值
    //若找见则返回元素在数组中的索引值，没有的话返回值为-1；


    public static int twoF(int[] arr, int key) {

        int max = arr.length - 1;     //最大索引
        int min = 0;                //最小索引

        while (max >= min) {

            int man = (max + min) / 2;    // 中间索引
            //判断
            if (key == arr[man]) {              //等于中间值，输出中间索引
                return man;
            } else if (key < arr[man]) {        //小于中间值，向左查找 man = max
                max = man - 1;
            } else {                            //大于中间值，向右查找 min = min;
                min = man + 1;
            }
        }
        return -1;
    }

}


